<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules" v-if="mode !== 'commission'">
                <!-- 审核模式 -->
                <el-form-item  label="审核" prop="is_disable">
                    <el-radio-group v-model="formData.is_disable">
                        <el-radio :label="1">通过</el-radio>
                        <el-radio :label="2">不通过</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <el-form ref="formRef_vice" :model="formData_vice" label-width="90px" :rules="formRules_vice" v-if="mode === 'commission'">
                <!-- 佣金比例设置模式 -->
                <el-form-item  label="佣金比例" prop="rate">
                    <div style="display: flex;flex-direction: column;">
                        <el-input-number 
                            v-model="formData_vice.rate" 
                            placeholder="请输入佣金比例"
                            style="width: 200px;"
                            maxlength="3"
                            @change="handleCommissionInput($event)"
                            :controls="false"
                        >
                            <template #append>%</template>
                        </el-input-number>
                        <div class="text-gray-500 text-sm mt-1">请输入1-100之间的整数</div>
                    </div>
                    
                </el-form-item>
            </el-form>
        </popup>
    </div>
  </template>
  
  <script lang="ts" setup name="hotelBasicEdit">
  import type { FormInstance } from 'element-plus'
  import Popup from '@/components/popup/index.vue'
  import { apiFamilyCheck, apiFamilyDetail, apiFamilyRate } from '@/api/family'
  import { timeFormat } from '@/utils/util'
  import type { PropType } from 'vue'
  import { reactive, ref, shallowRef, computed, nextTick } from 'vue'
  import feedback from '@/utils/feedback'
  const emit = defineEmits(['success', 'close'])
  const formRef = shallowRef<FormInstance>()
  const formRef_vice = shallowRef<FormInstance>()
  const popupRef = shallowRef<InstanceType<typeof Popup>>()
  const mode = ref('add')
  
  
  // 弹窗标题
  const popupTitle = computed(() => {
    if (mode.value === 'commission') {
      return '设置佣金比例'
    }
    return mode.value == 'edit' ? '审核家族/团体' : '审核家族/团体'
  })
  
  // 表单数据
  const formData = reactive({
    id: '',
    is_disable: ''
  })
  
  const formData_vice = reactive<{
    id: string | number,
    rate: any
  }>({
    id: '',
    rate: null
  })
  
  // 表单验证
  const formRules = reactive<any>({
    is_disable: [{
        required: true,
        message: '请选择审核结果',
        trigger: ['change']
    }]
  })
  
  const formRules_vice = reactive<any>({
    rate: [{
         required: true,
         message: '请输入佣金比例',
         trigger: ['blur']
     }, {
         validator: (rule: any, value: any, callback: any) => {
           if (!value) {
             callback()
             return
           }
           const num = parseInt(value)
           if (!/^[1-9]\d*$/.test(value) || num < 1 || num > 100) {
             callback(new Error('佣金比例必须为1-100之间的整数'))
           } else {
             callback()
           }
         },
         trigger: ['blur']
     }]
  })
  // 获取详情
  const setFormData = async (data: Record<any, any>) => {
    console.log(data)
    if(mode.value === 'commission'){
        formData_vice.id = data.id
        for (const key in formData_vice) {
            if (data[key] != null && data[key] != undefined) {
                //@ts-ignore
                formData_vice[key] = data[key]
            }
        }
    }else{
        for (const key in formData) {
            if (data[key] != null && data[key] != undefined) {
                //@ts-ignore
                formData[key] = data[key]
            }
        }
    }

    
    
    
  }
  
  const getDetail = async (row: Record<string, any>) => {
    const data = await apiFamilyDetail({
        id: row.id
    })
    setFormData(data)
  }
  
  
  // 处理佣金比例输入
   const handleCommissionInput = (event: any) => {
        console.log(event)
     // 只允许输入数字，并限制在1-100范围内
     let numericValue = event.toString().replace(/[^0-9]/g, '')
     if (numericValue && parseInt(numericValue) > 100) {
       numericValue = '100'
     }
     formData_vice.rate = Number(numericValue)
   }
  
  // 提交按钮
  const handleSubmit = async () => {
    if(mode.value === 'commission'){
        await formRef_vice.value?.validate()
        const data = { ...formData_vice }
        await apiFamilyRate({ ...data })
        feedback.msgSuccess('设置成功')
    }else{
        await formRef.value?.validate()
        const data = { ...formData }
        // 审核的API调用
        await apiFamilyCheck(data)
        feedback.msgSuccess('审核成功')
    }
    popupRef.value?.close()
    emit('success')
  }
  
  //打开弹窗
  const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
  }
  
  // 关闭回调
  const handleClose = () => {
    emit('close')
  }
  
  
  
  defineExpose({
    open,
    setFormData,
    getDetail
  })
  </script>
  